<?php
//if(!isset($base_url)) exit('No direct script access allowed');
class friend_model extends CI_Model
{
	public $table_name='friend';
	function __construct()
	{
		parent::__construct();
		
		$config['hostname'] = 'localhost';
		$config['username'] = 'root';
		$config['password'] = '';
		$config['database'] = 'helloworld';
		$config['dbdriver'] = 'mysql';
		$config['dbprefix'] = '';
		$config['pconnect'] = TRUE;
		$config['db_debug'] = TRUE;
		$config['cache_on'] = FALSE;
		$config['cachedir'] = '';
		$config['char_set'] = 'utf8';
		$config['dbcollat'] = 'utf8_general_ci';
		$config['swap_pre'] = '';
		$config['autoinit'] = TRUE;
		$config['stricton'] = FALSE;
		//@@@@@@testers: check the database name before start!!
		$this->load->database($config);
	}

	
	function get_my_friends()
	{
		$this->db->select('user.userid,
				user.fullname,
				user.gender,
				user.interest,
				user.language,
				user.description,
				user.location,
				friend.isvalid');
		$this->db->from('user');
		$this->db->join('friend', 'friend.friendid=user.userid');
		$this->db->where('friend.userid',$this->session->userdata('userid'));
		return $this->db->get();
		
	}
	
	function is_my_friend($friendid)
	{
		$this->db->where('userid',$this->session->userdata('userid') );
		$this->db->where('friendid', $friendid);
		$this->db->where('isvalid',true);
	
		return ($this->db->count_all_results($this->table_name) == 1);
	}
	function add_friend($friendid)
	{
		$new_friend['friendid'] = $friendid;
		$new_friend['userid'] = $this->session->userdata('userid');
		$new_friend['isvalid'] = true;
		$this->db->insert($this->table_name, $new_friend);
	}
	
	function delete_friend($friendid)
	{
		$this->db->where('friendid', $friendid);
		$this->db->where('userid',   $this->session->userdata('userid') );
		$new_friend['isvalid'] = false;
		$this->db->update($this->table_name, $new_friend);
	}
	
	/*
	function apply($friendid)
	{
		$new_friend['friendid'] = $friendid;
		$new_friend['userid'] = $this->session->userdata('userid');
		$new_friend['isconfirmed'] = false;
		$new_friend['isvalid'] = true;
		$this->db->insert($this->table_name, $new_link);
	}
	function confirm_friend($friendid)
	{
		$this->db->where('friendid', $friendid);
		$this->db->where('userid',   $this->session->userdata('userid') );
		$new_friend['isconfirmed'] = true;
		$this->db->update($this->table_name, $new_friend);
	}*/
	
	
	function ChangeQueryResultToArray($query)
	{
		if($query->num_rows() > 0)
		{
			foreach ($query->result() as $row)
			{
				$data[] = $row;
			}
			return $data;
		}
	}
	
}
?>